package com.coldchain.message.im.service.impl;

import com.coldchain.common.redis.RedisUtils;
import com.coldchain.message.im.base.BaseIMAccount;
import com.coldchain.message.im.enums.IMType;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;

@Service
public class IMAccountService {
    private static final Logger log= LoggerFactory.getLogger(IMAccountService.class);

    private static Random rand = new Random();
    @Autowired
    private RedisUtils redisUtils;
    private static  final String IMACCOUNT_KEY="im_account";




    public void init(){
            for (IMType type:IMType.values()) {
                if(redisUtils.getRMap(IMACCOUNT_KEY).get(type.name())==null){
                    redisUtils.getRMap(IMACCOUNT_KEY).put(type.name(),type.getDefalutAccount());
                }

            }

    }

    public <T extends BaseIMAccount> List<T> getAll(){
        List<T> accounts=new ArrayList<>();
        redisUtils.getRMap(IMACCOUNT_KEY).readAllMap().forEach((k,v)->{
            accounts.add((T) v);
        });
        return accounts;
    }

    public <T extends BaseIMAccount> T getAccountByType(IMType type){
        return getAccountByType(type.name());
    }
    public <T extends BaseIMAccount> T getAccountByType(String type){
        return (T) redisUtils.getRMap(IMACCOUNT_KEY).get(type);
    }

    public BaseIMAccount  getAccount(){
        List<BaseIMAccount> accounts=getAll();
        if(accounts==null || accounts.isEmpty()){
            return null;
        }
        if(accounts.size()==1 && accounts.get(0).isOpen()){
            return accounts.get(0);
        }
        List<BaseIMAccount> opens=new ArrayList<>();
        getAll().forEach((k)->{
             if(k.isOpen()){
                 opens.add(k);
             }
        });
        if(opens.isEmpty()){
            return null;
        }

        return  opens.get(rand.nextInt(opens.size()-1));
    }

    public <T extends BaseIMAccount> void editAccount(T account){
        redisUtils.getRMap(IMACCOUNT_KEY).putAsync(account.getImType(),account);
    }
}
